package com.sgb.trip.view.activity;

import android.os.CountDownTimer;
import android.util.TypedValue;
import android.view.View;

import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.fondesa.recyclerviewdivider.DividerDecoration;
import com.sgb.link.router.PathTrip;
import com.sgb.trip.R;
import com.sgb.trip.databinding.TripActivitySelfOrderDetailBinding;
import com.sgb.trip.entity.FlightOrderDetailEntity;
import com.sgb.trip.view.adapter.InsureServiceDetailAdapter;
import com.sgb.trip.view.adapter.PassengerFromDetailAdapter;
import com.sgb.trip.view.widget.FlightOrderDetailPopWindow;
import com.sgb.trip.viewmodel.FlightOrderDetailSelfModel;
import com.swgk.core.base.model.entity.RouterKey;
import com.swgk.core.common.base.BaseActivity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.DateUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.NumberUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Time:2021/10/9
 * Author:黄淋
 * Description:用户中心机票订单详情
 */
@Route(path = PathTrip.FlightOrdersDetailSelfActivity)
public class FlightOrdersDetailSelfActivity extends BaseActivity<FlightOrderDetailSelfModel, TripActivitySelfOrderDetailBinding> {
    @Autowired(name = RouterKey.STRING, desc = "订单号")
    String orderNo;

    private boolean flag = false;

    private int passengerCount;

    private FlightOrderDetailPopWindow detailPopWindow;

    PassengerFromDetailAdapter adapter;
    InsureServiceDetailAdapter insureServiceDetailAdapter;
    private List<FlightOrderDetailEntity.PassengersBean> mPassengerList = new ArrayList<>();
    private FlightOrderDetailEntity mEntity;

    private String allAccount;

    @Override
    protected int layoutId() {
        return R.layout.trip_activity_self_order_detail;
    }

    @Override
    protected void createViewModel() {
        mViewModel = new ViewModelProvider(this).get(FlightOrderDetailSelfModel.class);
    }

    @Override
    protected void init() {
        ARouter.getInstance().inject(this);
        mBinding.actionBar.setOnBackClickListener(this);
        mBinding.llPassengerDetailEx.setOnClickListener(this);
        mBinding.tvCancelOrder.setOnClickListener(this);
        mBinding.tvApplyPay.setOnClickListener(this);
        mBinding.tvCheckDetail.setOnClickListener(this);

        mBinding.clOrderStatus.setVisibility(View.GONE);
        mBinding.nsvOrderDetail.setVisibility(View.GONE);
        mBinding.clBottomDetail.setVisibility(View.GONE);

        initAdapter();
        initWindow();
        DialogHelper.showProgressDialog(this, "加载中...").setCanceledOnTouchOutside(false);
        mViewModel.getFligtOrderDetail(orderNo);
        mViewModel.ldOrdersData.observe(this, this::setDetailData);
    }


    private void initAdapter() {
        adapter = new PassengerFromDetailAdapter(this, null);
        mBinding.rvPassengers.setLayoutManager(new LinearLayoutManager(this));
        mBinding.rvPassengers.setAdapter(adapter);
        DividerDecoration.builder(this)
                .colorRes(R.color.color_EDEDED)
                .size(1, TypedValue.COMPLEX_UNIT_PX)
                .build()
                .addTo(mBinding.rvPassengers);
    }

    /**
     * 初始化航班详情弹窗
     */
    private void initWindow() {
        detailPopWindow = new FlightOrderDetailPopWindow(this);

    }


    /**
     * 设置数据
     *
     * @param entity
     */
    private void setDetailData(FlightOrderDetailEntity entity) {
        mBinding.clOrderStatus.setVisibility(View.VISIBLE);
        mBinding.nsvOrderDetail.setVisibility(View.VISIBLE);
        mBinding.clBottomDetail.setVisibility(View.VISIBLE);

        mEntity = entity;
        passengerCount = entity.getPassengers().size();

        insureServiceDetailAdapter = new InsureServiceDetailAdapter(this, null, entity.getOrderPriceDetails().size() == 2, passengerCount);
        mBinding.rvInsureInfo.setLayoutManager(new LinearLayoutManager(this));
        mBinding.rvInsureInfo.setAdapter(insureServiceDetailAdapter);
        DividerDecoration.builder(this)
                .colorRes(R.color.color_EDEDED)
                .size(1, TypedValue.COMPLEX_UNIT_PX)
                .build()
                .addTo(mBinding.rvInsureInfo);
        switch (entity.getOrderStatus()) {
            case 0://待支付
                mBinding.tvOrderStatus.setText("待支付");
                mBinding.tvApplyPay.setVisibility(View.VISIBLE);
                mBinding.tvCancelOrder.setVisibility(View.VISIBLE);
                mBinding.ivOrderTimeOff.setVisibility(View.VISIBLE);

                long leftTime = entity.getOrderTime() + 20 * 60 * 1000 - System.currentTimeMillis();//下单时间后20分钟为截止时间
                if (leftTime > 0) {
                    CountDownTimer timer = new CountDownTimer(leftTime, 1000) {
                        @Override
                        public void onTick(long millisUntilFinished) {
                            String str = String.format("%s%s", "剩余", DateUtils.formatDate(millisUntilFinished, "mm分ss秒"));
                            mBinding.tvLeftTime.setText(str);
                        }

                        @Override
                        public void onFinish() {
                            mBinding.tvOrderStatus.setText("已取消");
                            mBinding.tvLeftTime.setText("因超时未支付订单已取消");
                            mBinding.ivOrderTimeOff.setVisibility(View.GONE);
                            mBinding.tvCancelOrder.setVisibility(View.GONE);
                            mBinding.tvApplyPay.setVisibility(View.GONE);
                        }
                    };
                    timer.start();
                } else {
                    mBinding.tvOrderStatus.setText("已取消");
                    mBinding.tvLeftTime.setText("因超时未支付订单已取消");
                    mBinding.ivOrderTimeOff.setVisibility(View.GONE);
                    mBinding.tvCancelOrder.setVisibility(View.GONE);
                    mBinding.tvApplyPay.setVisibility(View.GONE);
                }
                break;
            case 1://
                mBinding.tvOrderStatus.setText("待出票");
                break;
            case 2://
                mBinding.tvOrderStatus.setText("待出行");
                break;
            case 3://
                mBinding.tvOrderStatus.setText("已取消");
                mBinding.tvLeftTime.setText("订单已取消");
                mBinding.ivOrderTimeOff.setVisibility(View.GONE);
                mBinding.tvCancelOrder.setVisibility(View.GONE);
                mBinding.tvApplyPay.setVisibility(View.GONE);
                break;
            case 4://
                mBinding.tvOrderStatus.setText("出票失败");
                break;
            case 5://
                mBinding.tvOrderStatus.setText("已完成");
                break;
            case 6://
                mBinding.tvOrderStatus.setText("已取消");
                mBinding.tvLeftTime.setText("因超时未支付订单已取消");
                mBinding.tvCancelOrder.setVisibility(View.GONE);
                mBinding.tvApplyPay.setVisibility(View.GONE);
                break;
            case 7://
                mBinding.tvOrderStatus.setText("已关闭");
                break;
            case 8://
                mBinding.tvOrderStatus.setText("退款中");
                break;
            case 9://
                mBinding.tvOrderStatus.setText("已退款");
                break;
        }

        mBinding.tvOrderNumberValue.setText(entity.getOrderNo());
        mBinding.tvOrderTimeValue.setText(DateUtils.timestampToDateSecond(entity.getOrderTime()));

        //总价
        if (entity.getOrderPriceDetails().size() == 1) {
            double ticket = entity.getOrderPriceDetails().get(0).getTicketPrice();
            double tax = entity.getOrderPriceDetails().get(0).getAdultTax();
            double fuel = entity.getOrderPriceDetails().get(0).getAdultFuel();
            double insure = 0;
            List<FlightOrderDetailEntity.OrderPriceDetailsBean.InsurancePricesBean> listInsure = entity.getOrderPriceDetails().get(0).getInsurancePrices();
            for (int i = 0; i < listInsure.size(); i++) {
                insure += listInsure.get(i).getInsuranceAmount();
            }
            allAccount = NumberUtil.trim0(ticket + tax + fuel + insure);
            mBinding.tvAllPrice.setText("¥" + NumberUtil.format(entity.getOrderAmount(), 2));
        } else if (entity.getOrderPriceDetails().size() == 2) {
            double ticket = entity.getOrderPriceDetails().get(0).getTicketPrice();
            double tax = entity.getOrderPriceDetails().get(0).getAdultTax();
            double fuel = entity.getOrderPriceDetails().get(0).getAdultFuel();
            double insure = 0;
            List<FlightOrderDetailEntity.OrderPriceDetailsBean.InsurancePricesBean> listInsure = entity.getOrderPriceDetails().get(0).getInsurancePrices();
            for (int i = 0; i < listInsure.size(); i++) {
                insure += listInsure.get(i).getInsuranceAmount();
            }

            double ticketBack = entity.getOrderPriceDetails().get(1).getTicketPrice();
            double taxBack = entity.getOrderPriceDetails().get(1).getAdultTax();
            double fuelBack = entity.getOrderPriceDetails().get(1).getAdultFuel();

            double insureBack = 0;
            List<FlightOrderDetailEntity.OrderPriceDetailsBean.InsurancePricesBean> listInsureBack = entity.getOrderPriceDetails().get(1).getInsurancePrices();
            for (int i = 0; i < listInsureBack.size(); i++) {
                insureBack += listInsureBack.get(i).getInsuranceAmount();
            }
            allAccount = NumberUtil.trim0(ticket + tax + fuel + insure + ticketBack + taxBack + fuelBack + insureBack);
            mBinding.tvAllPrice.setText("¥" + NumberUtil.format(entity.getOrderAmount(), 2));
        }


        //航班详情
        if (entity.getFlights() != null && entity.getFlights().size() == 1) {
            FlightOrderDetailEntity.FlightsBean bean = entity.getFlights().get(0);
            mBinding.rlChooseBack.setVisibility(View.GONE);
            mBinding.tvTo.setVisibility(View.GONE);
            setData(bean);
        } else if (entity.getFlights() != null && entity.getFlights().size() == 2) {
            mBinding.rlChooseBack.setVisibility(View.VISIBLE);
            mBinding.tvTo.setVisibility(View.VISIBLE);
            FlightOrderDetailEntity.FlightsBean bean = entity.getFlights().get(0);
            FlightOrderDetailEntity.FlightsBean bean1 = entity.getFlights().get(1);
            if (bean.isFromFlight()) {//去程
                setData(bean);
                setBackData(bean1);
            } else {
                setData(bean1);
                setBackData(bean);

            }
        }

        //乘客
        mPassengerList = entity.getPassengers();
        if (mPassengerList != null && mPassengerList.size() <= 2) {
            adapter.setDatas(mPassengerList);
            mBinding.llPassengerDetailEx.setVisibility(View.GONE);
        } else if (mPassengerList != null && mPassengerList.size() > 2) {
            mBinding.llPassengerDetailEx.setVisibility(View.VISIBLE);
            adapter.setDatas(mPassengerList.subList(0, 2));
        }

        //联系人
        mBinding.tvContractNameValue.setText(entity.getLinkName());
        mBinding.tvContractPhoneValue.setText(entity.getLinkPhone());

        //保险
        List<FlightOrderDetailEntity.OrderPriceDetailsBean.InsurancePricesBean> insureArrayList = entity.getOrderPriceDetails().get(0).getInsurancePrices();
        if (insureArrayList != null && insureArrayList.size() > 0) {
            insureServiceDetailAdapter.setDatas(insureArrayList);
        } else {
            mBinding.llInsureLayout.setVisibility(View.GONE);
        }
    }


    /**
     * 设置去程和单程的数据
     *
     * @param entity
     */
    private void setData(FlightOrderDetailEntity.FlightsBean entity) {
        if (entity != null) {
            String level = "";
            switch (entity.getCabinLevel()) {
                case 1:
                    level = "经济舱";
                    break;
                case 2:
                    level = "公务舱";
                    break;
                case 3:
                    level = "头等舱";
                    break;
            }
            String builder = DateUtils.formatDate(entity.getFromDateTime(), "MM月dd日") +
                    " " + entity.getWeekDay() +
                    "   " +
                    entity.getFromCity() +
                    " → " +
                    entity.getToCity() + " " + level;
            mBinding.tvTimeCity.setText(builder);
        }
        if (entity != null) {
            mBinding.tvStartAirport.setText(entity.getFromAirport() + entity.getFromTerminal());
            mBinding.tvArriveAirport.setText(entity.getToAirport() + entity.getToTerminal());
            mBinding.tvFlightName.setText(entity.getAirlineName() + entity.getFlightNo());
            mBinding.tvFlightCode.setText(entity.getCraftType());
            mBinding.tvFlightFood.setText(entity.getHasMeals());

            String fromDate = DateUtils.timestampTo13DateNos(entity.getFromDateTime());
            String toDate = DateUtils.timestampTo13DateNos(entity.getToDateTime());
            if (!fromDate.equals(toDate)) {
                mBinding.tvPlusDay.setVisibility(View.VISIBLE);
            } else {
                mBinding.tvPlusDay.setVisibility(View.GONE);
            }
            mBinding.tvStartTime.setText(DateUtils.timestampTo13Date2(entity.getFromDateTime()));
            mBinding.tvArriveTime.setText(DateUtils.timestampTo13Date2(entity.getToDateTime()));

            mBinding.tvDuration.setText(String.format("%sh%sm", NumberUtil.trim0(entity.getFlyDuration().split(":")[0], 0),
                    NumberUtil.trim0(entity.getFlyDuration().split(":")[1], 0)));
            Glide.with(this).load(entity.getAirlineLogo()).into(mBinding.ivLogo);

        }

    }

    /**
     * 设置返程数据
     *
     * @param entity
     */
    private void setBackData(FlightOrderDetailEntity.FlightsBean entity) {
        if (entity != null) {
            String level = "";
            switch (entity.getCabinLevel()) {
                case 1:
                    level = "经济舱";
                    break;
                case 2:
                    level = "公务舱";
                    break;
                case 3:
                    level = "头等舱";
                    break;
            }
            String builder = DateUtils.formatDate(entity.getFromDateTime(), "MM月dd日") +
                    " " + entity.getWeekDay() +
                    "   " +
                    entity.getFromCity() +
                    " → " +
                    entity.getToCity() + " " + level;
            mBinding.tvTimeCityBack.setText(builder);
        }
        if (entity != null) {
            mBinding.tvStartAirportBack.setText(entity.getFromAirport() + entity.getFromTerminal());
            mBinding.tvArriveAirportBack.setText(entity.getToAirport() + entity.getToTerminal());
            mBinding.tvFlightNameBack.setText(entity.getAirlineName() + entity.getFlightNo());
            mBinding.tvFlightCodeBack.setText(entity.getCraftType());
            mBinding.tvFlightFoodBack.setText(entity.getHasMeals());

            String fromDate = DateUtils.timestampTo13DateNos(entity.getFromDateTime());
            String toDate = DateUtils.timestampTo13DateNos(entity.getToDateTime());
            if (!fromDate.equals(toDate)) {
                mBinding.tvPlusDayBack.setVisibility(View.VISIBLE);
            } else {
                mBinding.tvPlusDayBack.setVisibility(View.GONE);
            }
            mBinding.tvStartTimeBack.setText(DateUtils.timestampTo13Date2(entity.getFromDateTime()));
            mBinding.tvArriveTimeBack.setText(DateUtils.timestampTo13Date2(entity.getToDateTime()));

            mBinding.tvDurationBack.setText(String.format("%sh%sm", NumberUtil.trim0(entity.getFlyDuration().split(":")[0], 0),
                    NumberUtil.trim0(entity.getFlyDuration().split(":")[1], 0)));
            Glide.with(this).load(entity.getAirlineLogo()).into(mBinding.ivLogoBack);
        }
    }


    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.iv_back_red) {//返回
            finish();
        } else if (view.getId() == R.id.ll_passenger_detail_ex) {//展开
            mBinding.ivPassengerDetailEx.setRotation(180);

            if (flag) {
                adapter.setDatas(mPassengerList);
                mBinding.tvPassengerDetailEx.setText("收起");
                mBinding.ivPassengerDetailEx.setRotation(180);
            } else {
                List<FlightOrderDetailEntity.PassengersBean> moreFive = new ArrayList<>();
                for (int i = 0; i < 2; i++) {
                    moreFive.add(mPassengerList.get(i));
                }
                adapter.setDatas(moreFive);
                mBinding.tvPassengerDetailEx.setText("展开");
                mBinding.ivPassengerDetailEx.setRotation(0);
            }

            flag = !flag;
        } else if (view.getId() == R.id.tv_cancel_order) {//取消订单
            MToast.showToast(FlightOrdersDetailSelfActivity.this, "功能开发中");
//            RoundDialogHelper.showDialog(FlightOrdersDetailSelfActivity.this, "提示", "确定要取消该订单吗？", "取消", "确定", new RoundDialogHelper.DialogFunction() {
//                @Override
//                public void normalRoundDialog() {
//                    //todo 取消订单
//
//                }
//            });
        } else if (view.getId() == R.id.tv_apply_pay) {//申请付款
            MToast.showToast(FlightOrdersDetailSelfActivity.this, "功能开发中");
        } else if (view.getId() == R.id.tv_check_detail) {//明细
            if (detailPopWindow != null) {
                detailPopWindow.showDownPopwindow(mBinding.clBottomDetail, true);
                detailPopWindow.backgroundAlpha(0.5f);
                if (passengerCount != 0) {
                    detailPopWindow.setDetailDataShow(mEntity, allAccount, passengerCount);
                }
            }
        }
    }
}
